package com.flower.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.flower.domain.ApiResult;
import com.flower.domain.entity.QiNiuEntity;
import com.flower.service.IQiNiuService;
import com.flower.service.UploadService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

/**
 * 文件上传控制层
 */
@RestController
public class UploadFileController {

    @Resource
    private UploadService uploadService;
    @Resource
    private IQiNiuService qiNiuService;

    @PostMapping("/upload")
    public ApiResult<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ApiResult.fail("上传的文件为空");
        }
        // 构造文件名
        String fileName = file.getOriginalFilename();
        String fileType = StrUtil.subAfter(fileName, ".", true);
        String newFileName = System.currentTimeMillis() + "." + fileType;
        // 临时文件保存的路径和文件名，这个路径要存在！
        String tempPath = "D:/temp/" + newFileName;
        // 生成临时文件
        File newFile = new File(tempPath);
        try {
            // 复制一份文件 文件出现
            file.transferTo(newFile);
            // 将新生成文件上传至七牛云
            QiNiuEntity qiNiu = qiNiuService.uploadFile(newFile);
            // 删除复制后的文件
            FileUtil.del(newFile);

            if (qiNiu != null) {
                // 返回结果
                System.out.println(qiNiu);
                return ApiResult.ok(newFileName, "上传成功");
            }
            // 返回结果
            return ApiResult.fail("上传失败，请重试");
        } catch (Exception e) {
            return ApiResult.fail("上传失败，请重试");
        }
    }
}
